/*
 * DA3.c
 *
 * Created: 2/27/2014 1:04:08 PM
 *  Author: Omar Salazar
 */ 

#include <avr/io.h>
#include <avr/interrupt.h>

volatile int count = 0;	//global interrupt value
volatile int count16 = 0;	//16 pulses
ISR (TIMER1_OVF_vect)
{		
	cli();					//disables interrupt
	TIFR1 = 0x02;				//Clear the TIFR1 flag
	TCCR0B = 0x06;			//WGM = 000 for normal, CS = 110 for external connect to T0
	TCCR0A = 0x00;			//WGM = 000  COM0A = 00  COM0B = 00  for normal
	
	count++;				//increment the count value to toggle
	count16++;				//increment the count 16 pulses value
//The two if statements below will feed T0 because it was set as an external clock
	if(count == 1)   //rising edge of T0
	{
		PORTC |= (1 << PORTC0);	//feed a one to T0
	}
	if (count == 2)   //falling edge of T0
	{
		PORTC &= ~(1 << PORTC0);	//feed a zero to T0
		count = 0;			//reset the counter
	}
	PORTB = TCNT0;			//Set PORTB to display the value of T0
	
	TCNT1 = 0xFE17;		//load the value of 65047 for the .5 second delay
	TCCR1B = 0x05;		//Load the NORMAL mode, prescaler of 1024
	TCCR1A = 0x00;		//and WGM = 0000 and CS = 101
	sei();				//enables the interrupt value
}
ISR (INT0_vect) //this interrupt will be triggered by the falling edge of PC0
{
	cli();					//disables interrupt
	if(count16 == 32)			//check for 32 because count16 was incremented on rising and falling edge
	{
		PORTC |= (1 << PORTC1);	//turn on PC1 which corresponds to the 9th LED
	}
	if(count16 == 64)	//catch the 2nd falling edge to toggle off PC1
	{
		PORTC &= ~(1 << PORTC1);		//turn off PC1
		count16 = 0;			//reset the count16 counter
	}
	sei();
}

int main(void)
{
	DDRB = 0xFF;				//Set PORTB for output
	DDRC |= (1<<PORTC0)|(1<<PORTC1);	//Set PC0 and PC1 for ouput  (can also be set like this: DDRC=0x05
	EICRA |= (1<<ISC01);			//the falling edge of INT0 generates an interrupt request
	EIMSK |= (1 << INT0);		//enable the external int0
	TIMSK1 = 0x01;			//enable overflow counter interrupt
	sei();					//enable interrupts
    while(1)
    {
        TCNT1 = 0xFE17;			//load the value of 65047 for the .5 second delay
	 TCCR1B = 0x05;		//Load the NORMAL mode, prescaler of 1024
	 TCCR1A = 0x00;		//and WGM = 0000 and CS = 101
	 while(1)
	 {
		//This will be interrupted
	 }
    }
}
